﻿using System;
using System.Collections.Generic;
using System.Text;
using DimensionsHelper.Common.Contracts.TableFormatter.Options;
using DimensionsHelper.Common.Contracts.Excel;

namespace DimensionsHelper.Services.TableFormatter;

internal static class TableFormatterHelper
{
    internal static List<(string Text, bool IsUpper)> GroupSigChars(string sigText)
    {
        var result = new List<(string Text, bool IsUpper)>();
        var builder = new StringBuilder();

        for (var i = 0; i < sigText.Length; i++)
        {
            var c = sigText[i];
            var isUpper = char.IsUpper(c);

            if (builder.Length > 0 && isUpper != char.IsUpper(builder[^1]))
            {
                result.Add((builder.ToString(), !isUpper));
                builder.Clear();
            }

            builder.Append(c);

            if (i == sigText.Length - 1)
            {
                result.Add((builder.ToString(), isUpper));
            }
        }

        return result;
    }

    internal static void MergeEmptyCells(IExcelRangeOperator range)
    {
        if (range.StartRow < range.EndRow)
        {
            return;
        }

        var row = range.StartRow;
        var startCol = range.StartColumn;
        var fromCol = startCol;
        var endCol = range.EndColumn;

        for (var i = startCol; i <= endCol; i++)
        {
            var cell = range.Worksheet.GetRange(row, i);
            var empty = cell.IsEmpty();

            if (empty && i != endCol)
            {
                continue;
            }

            var toCol = i - 1;

            if (i == endCol && empty)
            {
                toCol = i;
            }

            if (toCol - fromCol > 0)
            {
                range.Worksheet.GetRange(row, fromCol, row, toCol).Merge();
            }

            fromCol = i;
        }
    }

    internal static bool TryGetSectionDefinitionInText(ref string text, int startPosition,
        TableSectionFeature feature, out string sectionText)
    {
        sectionText = string.Empty;

        if (text.Length < startPosition)
        {
            return false;
        }

        if (string.IsNullOrEmpty(feature.Left) || string.IsNullOrEmpty(feature.Right))
        {
            return false;
        }

        if (!text.Substring(startPosition, feature.Left.Length).Equals(feature.Left))
        {
            return false;
        }

        var rightIndex = text.IndexOf(feature.Right, StringComparison.Ordinal);

        if (rightIndex <= startPosition + feature.Left.Length)
        {
            return false;
        }

        sectionText = text.Substring(startPosition + feature.Left.Length,
            rightIndex - startPosition - feature.Left.Length);
        text = rightIndex == text.Length - 1 ? "" : text[(rightIndex + 1)..];
        return true;
    }
}